<template>
  <div style="height: 100%; width: 100%">
    <t-card>
      <t-row style="margin-top: 25px">
        <t-col :span="12" class="tableTitle">员工基本信息调查表</t-col>
      </t-row>
      <t-row style="margin-bottom: 0px">
        <t-col :span="9"></t-col>
        <t-col :span="1"
          ></t-col
        >
        <t-col :span="1"
          >
          <!-- <t-link
            @click="handlEdit"
            theme="primary"
            hover="color"
            :disabled="!selectedRowKeys.length"
            ><t-icon name="edit" size="large" /> 编辑</t-link
          > -->
          <t-link
            theme="primary"
            hover="color"
            @click="createModalVisible = true"
            ><t-icon name="add" size="large" /> 创建</t-link
          >
          </t-col
        >
        <t-col :span="1"
          ><t-link
            @click="handleDel"
            theme="primary"
            hover="color"
            :disabled="!selectedRowKeys.length"
            ><t-icon name="delete" size="large" /> 删除</t-link
          ></t-col
        >
      </t-row>
      <t-row>
        <t-col
          :span="12"
          style="display: flex; justify-content: center; align-items: center"
        >
          <t-table
            ref="table"
            style="width: 100%"
            rowKey="id"
            :data="tableListData"
            :columns="colData"
            stripe
            bordered
            resizable
            bottomContent="———— 内部资料请勿拍照 ————"
            dragSort="row"
            :selected-row-keys="selectedRowKeys"
            @select-change="onSelectRow"
            :pagination="listPagination"
            :editable-row-keys="editableRowKeys"
            @row-edit="onRowEdit"
            @row-validate="onRowValidate"
            @validate="onValidate"
          />
        </t-col>
      </t-row>
    </t-card>
    <t-dialog
      header="Create"
      :visible="createModalVisible"
      :footer="false"
      :onClose="handleCloseCreateModal"
    >
      <t-form
        ref="form"
        :data="formData"
        colon
        :rules="allRule"
        @submit="onSubmit"
      >
        <t-form-item label="id" help="默认id锁定" name="id">
          <t-input v-model="formData.id" disabled></t-input>
        </t-form-item>
        <t-form-item label="姓名" name="name">
          <t-input
            v-model="formData.name"
            placeholder="请输入用户名"
            clearable
          ></t-input>
        </t-form-item>
        <t-form-item label="耗时" name="times">
          <t-input-number v-model="formData.times" max="10" min="1" />
        </t-form-item>
        <t-form-item label="职位" name="jobs">
          <t-select
            v-model="formData.jobs"
            class="demo-select-base"
            clearable
            filterable
            placeholder="请选择您的职位"
          >
            <t-option
              v-for="item in jobArr"
              :value="item.label"
              :label="item.label"
              :key="item.value"
            >
              {{ item.label }}
            </t-option>
          </t-select>
        </t-form-item>
        <t-form-item label="签署方式" name="types">
          <t-select
            v-model="formData.types"
            class="demo-select-base"
            clearable
            filterable
            placeholder="请选择您的签署方式"
          >
            <t-option
              v-for="item in typeArr"
              :value="item.label"
              :label="item.label"
              :key="item.value"
            >
              {{ item.label }}
            </t-option>
          </t-select>
        </t-form-item>

        <t-form-item label="工资" name="salary">
          <t-input
            v-model="formData.salary"
            placeholder="请输入您的工资"
            suffix="元"
          ></t-input>
        </t-form-item>

        <t-form-item
          label="座右铭"
          help="说出你内心为之奋斗的那团火"
          name="detailEvent"
        >
          <t-textarea
            v-model="formData.detailEvent"
            placeholder="请输入您的座右铭"
          ></t-textarea>
        </t-form-item>

        <t-form-item
          style="
            margin-left: 100px;
            margin-top: 25px;
            display: flex;
            justify-content: flex-end;
          "
        >
          <t-space size="10px">
            <t-button theme="default" @click="handleCloseCreateModal">
              Cancel
            </t-button>
            <t-button theme="primary" type="submit"> Create </t-button>
            <!-- <t-button theme="default" variant="base" type="reset"> 重置 </t-button>
        <t-button theme="default" variant="base" @click="handleClear"> 清空校验结果 </t-button>
        <t-button theme="default" variant="base" @click="clearFieldsValidateResult"> 清除指定字段的校验结果 </t-button> -->
          </t-space>
        </t-form-item>
      </t-form>
    </t-dialog>
  </div>
</template>

<script lang="jsx">
import { Input, InputNumber, Select } from "tdesign-vue";
import {
  ErrorCircleFilledIcon,
  CheckCircleFilledIcon,
  CloseCircleFilledIcon,
  //   Icon
} from "tdesign-icons-vue";
import { mockList, allJobs, allTypes } from "../../mock/tableList";
const formD = {
  id: mockList.length + 1,
  name: "",
  times: 1,
  jobs: "",
  types: "",
  salary: "",
  detailEvent: "",
};
export default {
  mounted() {
    this.resize();
  },
  components: {
    // Icon
  },
  data() {
    return {
      editableRowKeys: [],
      tableListData: this.setNewTableData(),
      jobArr: [...allJobs],
      typeArr: [...allTypes],
      createModalVisible: false,
      // colData: [...mockCol],
      selectedRowKeys: [],
      listPagination: {
        current: 1,
        pageSize: 10,
        defaultCurrent: 1,
        defaultPageSize: 10,
        total: this.setNewTableData().length,
        showJumper: true,
        onChange: (pageInfo) => {
          const { current, pageSize } = pageInfo;
          this.listPagination.current = current;
          this.listPagination.pageSize = pageSize;
        },
      },
      formData: {
        ...formD,
      },
      allRule: {
        name: [
          { required: true, message: "用户名必填", type: "error" },

          {
            validator: (val) => val.length <= 5,
            message: "内容文本长度不能超过 5 个字",
          },
        ],
        times: [
          { required: true, message: "兄弟，这个必填", type: "error", max: 10 },
          {
            validator: (val) => val <= 10,
            message: "都设置不允许超过10天了，你怎么还往高了输入",
          },
          // 自定义校验规则：不同的值可以有不同的校验结果，不同的校验类型
        ],
        salary: [
          { required: true, message: "请填写您的工资", type: "error" },
          { pattern: !/[^0-9]/g, message: "工资必须为数字" },
          // 自定义校验规则：自定义异步校验规则
        ],
        types: [
          { required: true, message: "请选择签署方式", type: "error" },
          // 自定义校验规则：自定义异步校验规则
        ],
      },
      editMap: {},
      currentSaveId: '',
    };
  },
  computed: {
    colData() {
      return [
        {
          colKey: "row-select",
          type: "multiple",
          // 禁用行选中方式一：使用 disabled 禁用行（示例代码有效，勿删）。disabled 参数：{row: RowData; rowIndex: number })
          // 这种方式禁用行选中，当前行会添加行类名 t-table__row--disabled，禁用行文字变灰
          // disabled: ({ rowIndex }) => rowIndex === 1 || rowIndex === 3,

          // 禁用行选中方式二：使用 checkProps 禁用行（示例代码有效，勿删）
          // 这种方式禁用行选中，行文本不会变灰
          //   checkProps: ({ rowIndex }) => ({ disabled: rowIndex % 2 !== 0 }),
          width: 50,
        },
        { colKey: "id", title: "序列", width: 60, align: "center" },
        {
          colKey: "name",
          title: "姓名",
          width: 70,
          align: "center",
          edit: {
            // 1. 支持任意组件。需保证组件包含 `value` 和 `onChange` 两个属性，且 onChange 的第一个参数值为 new value。
            // 2. 如果希望支持校验，组件还需包含 `status` 和 `tips` 属性。具体 API 含义参考 Input 组件
            component: Input,
            // props, 透传全部属性到 Input 组件
            props: {
              clearable: true,
              autofocus: true,
              autoWidth: true,
            },
            // 校验规则，此处同 Form 表单
            rules: [
              { required: true, message: "不能为空" },
              {
                validator: (val) => val.length <= 5,
                message: "内容文本长度不能超过 5 个字",
              },
            ],
            showEditIcon: false,
          },
        },
        {
          colKey: "times",
          title: "填写耗时（天）",
          width: 80,
          align: "center",
          edit: {
            // 1. 支持任意组件。需保证组件包含 `value` 和 `onChange` 两个属性，且 onChange 的第一个参数值为 new value。
            // 2. 如果希望支持校验，组件还需包含 `status` 和 `tips` 属性。具体 API 含义参考 Input 组件
            component: InputNumber,
            // props, 透传全部属性到 Input 组件
            props: {
              clearable: true,
              autofocus: true,
              autoWidth: true,
              theme: "column"
            },
            // 校验规则，此处同 Form 表单
            rules: [
            { required: true, message: "兄弟，这个必填", type: "error", max: 10 },
          {
            validator: (val) => val <= 10,
            message: "都设置不允许超过10天了，你怎么还往高了输入",
          },
            ],
            showEditIcon: false,
          },
        },
        { colKey: "jobs", title: "当前职位", width: 120, align: "center",
        edit: {
            // 1. 支持任意组件。需保证组件包含 `value` 和 `onChange` 两个属性，且 onChange 的第一个参数值为 new value。
            // 2. 如果希望支持校验，组件还需包含 `status` 和 `tips` 属性。具体 API 含义参考 Input 组件
            component: Select,
            // props, 透传全部属性到 Input 组件
            props: {
              clearable: true,
              options: this.jobArr
            },
            // 校验规则，此处同 Form 表单
            rules: [
            { required: true, message: "请选择职业", type: "error"},
        
            ],
            showEditIcon: false,
          }, },

        {
          colKey: "types",
          title: "本人认可签署方式",
          width: 120,
          align: "center",
          cell: (h, { row }) => {
            // console.log(row)
            const statusNameListMap = {
              纸质签署: {
                label: "纸质签署",
                theme: "success",
                icon: <CheckCircleFilledIcon />,
              },
              手写: {
                label: "手写",
                theme: "danger",
                icon: <CloseCircleFilledIcon />,
              },
              电子签署: {
                label: "电子签署",
                theme: "warning",
                icon: <ErrorCircleFilledIcon />,
              },
              "--": {
                label: "机打",
                theme: "warning",
                icon: <ErrorCircleFilledIcon />,
              },
            };
            return (
              <t-tag
                shape="round"
                theme={statusNameListMap[row.types].theme}
                variant="light-outline"
              >
                {statusNameListMap[row.types].icon}
                {statusNameListMap[row.types].label}
              </t-tag>
            );
          },
        },
        { colKey: "salary", title: "工资（元）", width: 100, align: "center" },
        {
          colKey: "detailEvent",
          title: "个人座右铭",
          width: 180,
          align: "center",
        },
        {
          title: "操作栏",
          colKey: "operate",
          width: 120,
          align: "center",
          cell: (h, { row }) => {
            const editable = this.editableRowKeys.includes(row.id);
            return (
              <div
                style="display: flex;justify-content: space-evenly"
              >
                {!editable && (
                  <t-link
                    theme="primary"
                    hover="color"
                    data-id={row.id}
                    onClick={this.onEdit(row.id)}
                  >
                    编辑
                  </t-link>
                )}
                {editable && (
                  <t-link
                    theme="primary"
                    hover="color"
                    data-id={row.id}
                    onClick={this.onSave}
                  >
                    保存
                  </t-link>
                )}
                {editable && (
                  <t-link
                    theme="primary"
                    hover="color"
                    data-id={row.id}
                    onClick={this.onCancel}
                  >
                    取消
                  </t-link>
                )}
              </div>
            );
          },
        },
      ];
    },
  },
  methods: {
    onEdit(id) {
      return () => {
        if (!this.editableRowKeys.includes(id)) {
          this.editableRowKeys.push(id);
        }
      };
    },
    updateEditState(id) {
      const index = this.editableRowKeys.findIndex((t) => t === id);
      this.editableRowKeys.splice(index, 1);
    },
    onCancel(e) {
      const { id } = e.currentTarget.dataset;
      this.updateEditState(id);
      this.$refs.table.clearValidateData();
    },

    onSave(e) {
      console.log(this.$refs.table)
      const { id } = e.currentTarget.dataset;
      this.currentSaveId = id;
      console.log(this.$refs.table)
      // 触发内部校验，而后在 onRowValidate 中接收异步校验结果
      // 重点：受框架层面限制，如果是 EnhancedTable 请更为使用 this.$refs.tableRef.primaryTableRef.validateRowData(id)
      // this.$refs.tableRef.primaryTableRef.validateRowData(id).then((params) => {
      this.$refs.table.validateRowData(id).then((params) => {
        console.log("Event Table Promise Validate:", params);
        if (params.result.length) {
          const r = params.result[0];
          this.$message.error(`${r.col.title} ${r.errorList[0].message}`);
          return;
        }
        // 如果是 table 的父组件主动触发校验
        if (params.trigger === "parent" && !params.result.length) {
          const current = this.editMap[this.currentSaveId];
          if (current) {
            this.data.splice(current.rowIndex, 1, current.editedRow);
            this.$message.success("保存成功");
          }
          this.updateEditState(this.currentSaveId);
        }
      });
    },
    onValidate(params) {
      console.log("Event Table Data Validate:", params);
    },

    onRowValidate(params) {
      console.log("validate:", params);
    },
    onRowEdit(params) {
      const {
        row,

        // rowIndex,
        col,
        value,
      } = params;
      console.log(row,col,value,params)
      const oldRowData = this.editMap[row.key]?.editedRow || row;
      const editedRow = { ...oldRowData, [col.colKey]: value };
      this.editMap[row.key] = {
        ...params,
        editedRow,
      };

      // ⚠️ 重要：以下内容应用于全量数据校验（单独的行校验不需要）
      // const newData = [...this.data];
      // newData[rowIndex] = editedRow;
      // this.data = newData;
      // 或者
      // this.$set(this.data, rowIndex, editedRow);
    },

    handleDel() {
      let key = this.selectedRowKeys;
      key.map((item) => {
        this.tableListData.splice(item - 1, 1);
      });
      this.selectedRowKeys = [];
    },
    // handlEdit() {},
    handleCloseCreateModal() {
      this.createModalVisible = false;
    },
    resize() {
      window.onresize = function () {
        console.log("横向滚动条修复");
      };
    },
    setNewTableData() {
      let _data = mockList;
      _data.map((item) => {
        Object.keys(item).map((val) => {
          if (!item[val] == undefined) {
            item[val] = "--";
          }
          if (!item["jobs"]) {
            item["jobs"] = "默认职位";
          } else if (!item["detailEvent"]) {
            item["detailEvent"] = "让bug来的更猛烈些吧！";
          }
        });
      });
      return _data;
    },
    onSelectRow(value, { selectedRowData }) {
      console.log(selectedRowData);
      this.selectedRowKeys = value;
    },
    onSubmit(context) {
      if (context.validateResult === true) {
        this.$message.success("提交成功");
        this.tableListData.push(this.formData);
        this.setNewTableData();
        this.createModalVisible = false;
      } else {
        // console.log("Errors: ", context.validateResult);
        this.$message.warning(context.firstError);
      }
    },
    // 自定义异步校验器，使用 resolve 返回结果控制校验结果、校验信息、校验结果类型
  },
};
</script>

<style lang="less" scoped>
.t-row {
  margin-bottom: 25px;
}
.tableTitle {
  font-size: 30px;
  font-weight: 600;
}
:global(t-table__bottom-content) {
  margin-top: 20px;
}
</style>
